from django.shortcuts import render
from rest_framework.generics import ListAPIView,RetrieveAPIView,CreateAPIView,GenericAPIView
from rest_framework.viewsets import ModelViewSet
from apps.activitys.models import Gathering
from apps.activitys.serializers import ActivitySerializer,ActivityDetailSerializer
# Create your views here.
from apps.activitys.serializers import PageNum



class ActivityView(ListAPIView):
    #GET /gatherings/ 获取活动列表


    serializer_class = ActivitySerializer

    pagination_class  = PageNum
    #未排序
    queryset=Gathering.objects.all().order_by('-starttime')


class ActivityDetailView(RetrieveAPIView):
    # GET /gatherings/<int:pk>/ 获取单个活动详情

    queryset = Gathering.objects.filter(state=1)
    serializer_class = ActivityDetailSerializer

    #def get(self, request, pk):
       # return self.retrieve(request)
from rest_framework.response import Response



class ApplicationView(GenericAPIView):
    # GET /gatherings/{id}/join/

    queryset = Gathering.objects.filter(state=1)
    #serializer_class = ApplicationSerializer
    #pagination_class = PageNum

    # def get_queryset(self):
    #     # 提取keyword
    #     keyword = self.request.query_params.get('keyword')
    #     if keyword == '' or keyword is None:
    #         return Gathering.objects.all()
    #     else:
    #         return Gathering.objects.filter(name=keyword)

    def post(self, request, pk):
        user = request.user
        if not user:
            return Response ({'success': False, 'message': '请从新登陆'})
        activity = self.get_object()
              #users是Gathering 中间表字段名
        if user in activity.users.all():
            activity.users.remove(user)  # 删除数据
            activity.save()
            return Response({'success': True, 'message': '取消报名'})
        else:
            activity.users.add(user)  # 增加数据
            activity.save()
            return Response({'success': True, 'message': '报名成功'})

